import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:r_scan_example/scan_dialog.dart';
import 'package:r_scan/src/r_scan_camera.dart';

List<RScanCameraDescription> rScanCameras;

class RScanCameraDialog extends StatefulWidget {
  @override
  _RScanCameraDialogState createState() => _RScanCameraDialogState();
}

class _RScanCameraDialogState extends State<RScanCameraDialog> {
  RScanCameraController _controller;
  bool isFirst = true;
  bool isScan = true;
  int _autoFlashStat = 0;


  void initCamera() async {
    if (rScanCameras == null || rScanCameras.length == 0) {
      final result = await Permission.camera.status;
      if (result.isGranted) {
        rScanCameras = await availableRScanCameras();
        print('返回可用的相机：${rScanCameras.join('\n')}');
      } else {
        final result = await Permission.camera.request();
        if (result.isGranted) {
          rScanCameras = await availableRScanCameras();
          print('返回可用的相机：${rScanCameras.join('\n')}');
        } else {
          print('相机权限被拒绝，无法使用');
        }
      }
    }
    if (rScanCameras != null && rScanCameras.length > 0) {
      _controller = RScanCameraController(
          rScanCameras[0], RScanCameraResolutionPreset.high)
        ..addListener(() {
          final result = _controller.result;
          if (result != null) {
            if (isFirst) {
              Navigator.of(context).pop(result);
              isFirst = false;
            }
          }
        })
        ..initialize().then((_) {
          if (!mounted) {
            return;
          }
          setState(() {});
        });
    }
  }

  @override
  void initState() {
    super.initState();
    initCamera();
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (rScanCameras == null || rScanCameras.length == 0) {
      return Scaffold(
        body: Container(
          alignment: Alignment.center,
          child: Text('not have available camera'),
        ),
      );
    }
    if (!_controller.value.isInitialized) {
      return Container();
    }
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: <Widget>[
          ScanImageView(
            child: AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              child: RScanCamera(_controller),
            ),
          ),
          Row(
            children: [
              Container(
                padding: EdgeInsets.only(
                    bottom: 24 + MediaQuery.of(context).padding.bottom,
                    left: 12),
                child: Align(
                    alignment: Alignment.bottomCenter,
                    child: TextButton(
                      onPressed: () async {
                        await _controller.setFlashMode(false);
                        await _controller.setAutoFlashMode(false);
                        await _controller.stopScan();
                        isScan = false;
                        setState(() {
                          _autoFlashStat = 0;
                        });
                      },
                      child: Text('关闭扫描'),
                    )),
              ),
              Container(
                padding: EdgeInsets.only(
                    bottom: 24 + MediaQuery.of(context).padding.bottom,
                    left: 12),
                child: Align(
                    alignment: Alignment.bottomCenter,
                    child: TextButton(
                      onPressed: () async {
                        _controller.startScan();
                        isScan = true;
                      },
                      child: Text('开启扫描'),
                    )),
              ),
              Align(
                  alignment: Alignment.bottomCenter,
                  child: Padding(
                    padding: EdgeInsets.only(
                        bottom: 24 + MediaQuery.of(context).padding.bottom),
                    child: IconButton(
                        icon: Icon(_autoFlashStat == 2
                            ? Icons.flash_auto
                            : (_autoFlashStat == 1
                                ? Icons.flash_on
                                : Icons.flash_off)),
                        color: Colors.white,
                        iconSize: 46,
                        onPressed: () {
                          if (!isScan) {
                            setState(() {
                              _autoFlashStat = 0;
                            });
                            return;
                          }
                          if (_autoFlashStat == 2) {
                            _autoFlashStat = 0;
                          } else {
                            _autoFlashStat = _autoFlashStat + 1;
                          }
                          print('闪光灯状态:' + _autoFlashStat.toString());
                          if (_autoFlashStat == 2) {
                            _controller.setAutoFlashMode(true);
                            _controller.setFlashMode(false);
                          } else if (_autoFlashStat == 1) {
                            _controller.setFlashMode(true);
                            _controller.setAutoFlashMode(false);
                          } else {
                            _controller.setFlashMode(false);
                            _controller.setAutoFlashMode(false);
                          }
                          setState(() {});
                        }),
                  )),
            ],
          )
        ],
      ),
    );
  }

  Future<bool> getFlashMode() async {
    bool isOpen = false;
    try {
      isOpen = await _controller.getFlashMode();
    } catch (_) {}
    return isOpen;
  }
}
